package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func IPAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		ipList := []string{
			"127.0.0.2",
		}
		flag := false
		clientIP := c.ClientIP()
		for _, host := range ipList {
			if clientIP == host {
				flag = true
				break
			}
		}
		if !flag {
			c.String(200, "客户端IP不可访问。")
			c.Abort() //退出程序
		}
	}
}

func main() {
	r := gin.Default()
	r.Use(IPAuthMiddleware()) //全局中间件使用
	{

		r.GET("/test", func(c *gin.Context) {
			name := c.Query("name")
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  name,
			})
		})
	}

	r.Run()
}
